package cn.xuqiudong.console.module.timer.schedule.ddns.handler;

import cn.xuqiudong.common.util.JsonUtil;
import com.aliyun.alidns20150109.Client;
import com.aliyun.alidns20150109.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 描述:修改阿里云的域名解析， 因为使用的服务器是家用小主机，公网ip可能会改变
 * <a href="https://help.aliyun.com/document_detail/262062.html">Java SDK</a>
 * <a href="https://help.aliyun.com/document_detail/124923.html">DNS API快速入门</a>
 * @author Vic.xu
 * @since 2022-07-04 16:58
 */
public class AliDnsUtils {

    private static Logger logger = LoggerFactory.getLogger(AliDnsUtils.class);


    private String accessKeyId = "LTAI5tMpNnGkUaCViw4iVdGV";
    private String accessKeySecret = "5Jhqm7Wh0sHHTgYXZUcVHPnziOjUyY";

    private static final String DOMAIN = "xuqiudong.cn";
    private static final String KEYWORD = "";

    public Client client;

    public static volatile AliDnsUtils aliDnsUtils;

    /**
     * 获取实例
     * @param accessKeyId accessKeyId
     * @param accessKeySecret accessKeySecret
     * @return
     * @throws Exception ex
     */
    public static AliDnsUtils getInstance(String accessKeyId, String accessKeySecret) throws Exception {
        if (aliDnsUtils == null) {
            synchronized (AliDnsUtils.class) {
                if (aliDnsUtils == null) {
                    aliDnsUtils = new AliDnsUtils(accessKeyId, accessKeySecret);
                }
            }
        }
        return aliDnsUtils;
    }

    public AliDnsUtils(String accessKeyId, String accessKeySecret) throws Exception {
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        createClient();
    }

    /**
     * 使用AK&SK初始化账号Client
     * @return Client
     */
    private Client createClient() throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dns.aliyuncs.com";
        this.client = new Client(config);
        return this.client;
    }

    /**
     * 获得主域名
     * @return
     * @throws Exception
     */
    private DescribeDomainRecordsResponseBody.DescribeDomainRecordsResponseBodyDomainRecordsRecord getDomainDnsRecord() throws Exception {
        DescribeDomainRecordsRequest describeDomainRecordsRequest = new DescribeDomainRecordsRequest()
                .setDomainName(DOMAIN)
                .setKeyWord(KEYWORD);
        // 获取记录详情
        DescribeDomainRecordsResponse domainRecordsResponse = client.describeDomainRecords(describeDomainRecordsRequest);
        List<DescribeDomainRecordsResponseBody.DescribeDomainRecordsResponseBodyDomainRecordsRecord> record = domainRecordsResponse.getBody().getDomainRecords().getRecord();
        DescribeDomainRecordsResponseBody.DescribeDomainRecordsResponseBodyDomainRecordsRecord describeDomainRecordsResponseBodyDomainRecordsRecord = record.get(0);
        logger.info("获取解析记录：{}", JsonUtil.toJson(describeDomainRecordsResponseBodyDomainRecordsRecord));
        return describeDomainRecordsResponseBodyDomainRecordsRecord;
    }


    /**
     * DescribeDomains  查询账户下域名
     * @throws Exception
     */
    public void describeDomains() throws Exception {
        DescribeDomainsRequest req = new DescribeDomainsRequest();
        logger.info("查询域名列表(json)↓");
        try {
            DescribeDomainsResponse resp = client.describeDomains(req);
            //logger.info(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(resp)));
            JsonUtil.printJson(resp.getBody());
        } catch (TeaException error) {
            logger.error(error.message);
        } catch (Exception e) {
            TeaException error = new TeaException(e.getMessage(), e);
            logger.error(error.message);
        }
    }

    /**
     * 获取子域名解析记录列表
     */
    public DescribeSubDomainRecordsResponseBody.DescribeSubDomainRecordsResponseBodyDomainRecordsRecord subDomainRecords(String subDomain) {
        DescribeSubDomainRecordsRequest describeSubDomainRecordsRequest = new DescribeSubDomainRecordsRequest();
        describeSubDomainRecordsRequest.setSubDomain(subDomain);
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            DescribeSubDomainRecordsResponse describeSubDomainRecordsResponse = client.describeSubDomainRecordsWithOptions(describeSubDomainRecordsRequest, runtime);
            DescribeSubDomainRecordsResponseBody body = describeSubDomainRecordsResponse.getBody();
            DescribeSubDomainRecordsResponseBody.DescribeSubDomainRecordsResponseBodyDomainRecordsRecord record = body.getDomainRecords().getRecord().get(0);
            return record;
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            System.out.println(error.message);
            error.printStackTrace();
        } catch (Exception e) {
            TeaException error = new TeaException(e.getMessage(), e);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            System.out.println(error.message);
            e.printStackTrace();
        }
        return null;
    }

    public UpdateDomainRecordResponse update
            (DescribeSubDomainRecordsResponseBody.DescribeSubDomainRecordsResponseBodyDomainRecordsRecord record, String value) throws
            Exception {

        UpdateDomainRecordRequest updateDomainRecordRequest = new UpdateDomainRecordRequest();
        updateDomainRecordRequest.setRecordId(record.getRecordId());
        updateDomainRecordRequest.setRR(record.getRR());
        updateDomainRecordRequest.setType(record.getType());
        updateDomainRecordRequest.setValue(value);

        RuntimeOptions runtime = new RuntimeOptions();
        // 复制代码运行请自行打印 API 的返回值
        UpdateDomainRecordResponse updateDomainRecordResponse = client.updateDomainRecordWithOptions(updateDomainRecordRequest, runtime);
        return updateDomainRecordResponse;
    }


}


